package com.open.jacekkowalczyk.sql;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

/**
 * Hello world!
 */
public class Generator {

    public static void main(final String[] args) {
        final Generator generator = new Generator();
        final Options options = new Options();
        options.addOption("c", "ignorecomments", false, "ignore lines wich starts with #");
        options.addOption("t", "template", true, "path to the template file, REQUIRED");
        options.addOption("p", "params", true, "coma separated lits of params in form key=value, REQUIRED");
        options.addOption("h", "help", false, "prints help");

        final org.apache.commons.cli.CommandLineParser parser = new PosixParser();
        try {
            final CommandLine cmd = parser.parse(options, args);
            final boolean optionTPresent = cmd.hasOption("t");
            final boolean optionPPresent = cmd.hasOption("p");
            final boolean optionHPresent = cmd.hasOption("h");
            final boolean optionCPresent = cmd.hasOption("c");
            boolean displayHelp = true;
            boolean validOptions = true;

            if (!optionTPresent || !optionPPresent) {
                displayHelp = true;
                validOptions = false;
            }
            if (optionHPresent) {
                displayHelp = true;
            }
            if (validOptions) {
                // do generation
                displayHelp = false;
                final String template = cmd.getOptionValue("t");// to get the parameter value
                final String params = cmd.getOptionValue("p");// to get the parameter value
                generator.generate(template, params, optionCPresent);
            }
            if (displayHelp) {
                final HelpFormatter formatter = new HelpFormatter();
                final StringBuilder usageSb = new StringBuilder();
                usageSb
                    .append("java -jar sql-generator-1.0-SNAPSHOT-jar-with-dependencies.jar <-p key=value params> <-t templatePath> [-h]");
                final StringBuilder header = new StringBuilder();
                header.append("\nSQL-Generator\n");
                header.append("SQL-Generator:\n");
                header.append("generates sql queries based on some template, with given parameters");
                formatter.printHelp(usageSb.toString(), header.toString(), options,
                    "\nFor more information please check webpage http://my.application.com.example");
            }
        } catch (final ParseException e) {
            e.printStackTrace();
        }

    }

    public void generate(final String template, final String params, final boolean ignoreComments) {
        final Map<String, String> paramsMap = new HashMap<String, String>();
        System.out.println("--" + params);
        final String[] paramsArray = params.split(",");
        for (final String elem : paramsArray) {
            final String[] keyValue = elem.split("=");
            paramsMap.put(keyValue[0], keyValue[1]);
        }
        try {
            System.out.println(generate(template, paramsMap, ignoreComments));
        } catch (final IOException e) {
            e.printStackTrace();
        }

    }

    public String generate(final String filePath, final Map<String, String> params, final boolean ignoreComments)
        throws IOException {
        InputStream fis;

        fis = new FileInputStream(filePath);

        final InputStreamReader isr = new InputStreamReader(fis);
        final BufferedReader br = new BufferedReader(isr);
        final StringBuffer sb = new StringBuffer();

        String line;
        while ((line = br.readLine()) != null) {
            final String trimedLine = line.trim();
            if (ignoreComments) {
                if (!trimedLine.startsWith("#")) {
                    sb.append(trimedLine + "\n");
                }
            } else {
                sb.append(trimedLine + "\n");
            }

        }
        br.close();
        isr.close();
        fis.close();

        String content = sb.toString();

        for (final String key : params.keySet()) {
            final String keyTemplate = String.format("!%1$s!", key);
            content = content.replaceAll(keyTemplate, params.get(key));
        }
        return content;

    }

}
